<?php

namespace app\controllers\merchant\shop;


use app\models\shop\PreheatModel;
use app\models\shop\ShopGoodsModel;
use yii;
use yii\web\MerchantController;
use yii\db\Exception;


class PreheatController extends MerchantController
{

    public $enableCsrfValidation = false; //禁用CSRF令牌验证，可以在基类中设置

//    public function behaviors() {
//        return [
//            'token' => [
//                'class' => 'yii\filters\MerchantFilter', //调用过滤器
//                'only' => ['single'],//指定控制器应用到哪些动作
//               'except' => ['goods'], //指定控制器不应用到哪些动作
//            ]
//        ];
//    }

    public function actionList()
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数          
            $model = new PreheatModel();
            $params['merchant_id'] = yii::$app->session['uid'];
            if (isset($params['searchName'])) {
                if ($params['searchName'] != "") {
                    $params['name'] = ['like', "{$params['searchName']}"];
                }
                unset($params['searchName']);
            }

            $array = $model->do_select($params);
            if ($array['status'] == 200) {
                for ($i = 0; $i < count($array['data']); $i++) {
                    $array['data'][$i]['goods_id'] = json_decode($array['data'][$i]['goods_id'], true);
                    $array['data'][$i]['number'] = $array['data'][$i]['goods_id'];
                    if (is_array($array['data'][$i]['number'])) {
                        $array['data'][$i]['number'] = count($array['data'][$i]['number']);
                    } else {
                        $array['data'][$i]['number'] = 0;
                    }
                    $array['data'][$i]['format_start_time'] = date('Y-m-d H:i:s', $array['data'][$i]['start_time']);
                    $array['data'][$i]['format_end_time'] = date('Y-m-d H:i:s', $array['data'][$i]['end_time']);
                }
            }
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    public function actionSingle($id)
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $model = new PreheatModel();
            $params['id'] = $id;
            $array = $model->do_one($params);
            if ($array['status'] == 200) {
                $array['data']['format_start_time'] = date('Y-m-d H:i:s', $array['data']['start_time']);
                $array['data']['format_end_time'] = date('Y-m-d H:i:s', $array['data']['end_time']);
            }

            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    public function actionAdd()
    {
        if (yii::$app->request->isPost) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参
            $model = new PreheatModel();
            $params['merchant_id'] = yii::$app->session['uid'];
//            $must = ['name', 'key', 'pic_url'];
//            $rs = $this->checkInput($must, $params);
//            if ($rs != false) {
//                return $rs;
//            }
            if (isset($params['start_time'])) {
                $params['start_time'] = strtotime($params['start_time']);
            }
            if (isset($params['end_time'])) {
                $params['end_time'] = strtotime($params['end_time']);
            }
            $array = $model->do_add($params);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    public function actionUpdate($id)
    {
        if (yii::$app->request->isPut) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参
            $model = new PreheatModel();
            $where['id'] = $id;
            $where['merchant_id'] = yii::$app->session['uid'];
            //    $where['key'] = $params['key'];

            if (isset($params['start_time'])) {
                $params['start_time'] = strtotime($params['start_time']);
            }
            if (isset($params['end_time'])) {
                $params['end_time'] = strtotime($params['end_time']);
            }

            $array = $model->do_update($where, $params);

            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    public function actionGoods()
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $model = new ShopGoodsModel();
            $params['merchant_id'] = yii::$app->session['uid'];
            if (isset($params['searchName'])) {
                if ($params['searchName'] != "") {
                    $params['name'] = ['like', "{$params['searchName']}"];
                }
                unset($params['searchName']);
            }
            if (isset($params['time'])) {
                if ($params['time'] == 'today') {
                    $startTime = strtotime(date('Y-m-d'), time());
                    $endTime = $startTime + 24 * 3600;
                    $params['create_time'] = [['>=', $startTime], ['<=', $endTime]];
                    unset($params['type']);
                } else {
                    unset($params['type']);
                }
            }
            if (isset($params['id'])) {
                //  $where['or'] = ['or',['like', 'shop_user.nickname', $params['searchName']],['like', 'shop_order_group.goodsname', $params['searchName']]];
                $params['or'] = ['or', ['=', 'is_preheat', 0], ['=', 'is_preheat', $params['id']]];
                unset($params['id']);
            }
            $params['field'] = "id,pic_urls,name";
            $params['orderby'] = "is_preheat desc ,create_time desc";
            $array = $model->do_select($params);
            //   \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    public function actionGoodsUpdate($id)
    {
        if (yii::$app->request->isPut) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参
            $goodsModel = new ShopGoodsModel();

            $transaction = yii::$app->db->beginTransaction();
            $model = new PreheatModel();
            $preheat = $model->do_one(['id' => $id]);

            if ($preheat['data']['end_time'] < time()) {
                return result(500, "预热时间已过期");
            }
            try {
                if (isset($params['goods_id'])) {
                    if ($preheat['status'] == 200) {
                        if ($preheat['data']['goods_id'] != "") {
                            $goods_id = json_decode($preheat['data']['goods_id'], true);
                            $un_goods_id = array_merge(array_diff($goods_id, $params['goods_id']), array_diff($params['goods_id'], $goods_id));
                            $goodsModel->do_update(['id' => $un_goods_id], ['is_preheat' => 0, 'status' => 1]);
                        }
                    }
                    $res = $model->do_update(['id' => $id], ['goods_id' => json_encode($params['goods_id'])]);
                    if ($res['status'] == 200) {
                        $goodsModel->do_update(['id' => $params['goods_id']], ['is_preheat' => $id, 'status' => 2]);
                        $transaction->commit(); //只有执行了commit(),对于上面数据库的操作才会真正执行
                    }
                    return result(200, "选择成功");
                } else {
                    $res = $model->do_update(['id' => $id], ['goods_id' => ""]);
                    $goodsModel->do_update(['is_preheat' => $id], ['is_preheat' => 0, 'status' => 1]);
                    $transaction->commit(); //只有执行了commit(),对于上面数据库的操作才会真正执行
                    return $res;
                }

            } catch (Exception $e) {
                $transaction->rollBack(); //回滚
                return result(500, "选择失败");
            }
            return $res;
        } else {
            return result(500, "请求方式错误");
        }
    }


    public function actionDelete($id)
    {
        if (yii::$app->request->isDelete) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参
            $model = new PreheatModel();
            $params['id'] = $id;
            $params['merchant_id'] = yii::$app->session['uid'];
            $array = $model->do_delete($params);
            $goodsModel = new ShopGoodsModel();
            $goodsModel->do_update(['is_preheat' => $id], ['is_preheat' => 0, 'status' => 1]);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

}
